<#
    .AUTHOR
        cw50406@imcnam.ssmb.com  
    .GROUP
        RPA AA STE Support Team(dl.gt.cn.cstc.rpa.aa.ste@imcnam.ssmb.com)
    .VERSION
        2.0
    .Synopsis
        Check RDC Sessions
    .DESCRIPTION
        Check opened RDC Sessions and compare to the file ServersConfiguration.csv
    .EXAMPLE
        .\check_connected_rdc_sessions.ps1 c:\temp\test.log 12:23
        Check opened RDC Sessions with log file 'c:\temp\test.log' and autosysjob start time "12:23"
    .Update
        09/11/2017--optimize code with more clear comments structure
        08/29/2017--optimize email sending code with domain,env,node,running result ...
        08/17/2017--send notifications email to team
        08/01/2017--Optimize code structure
#>
param(
	[Parameter(Mandatory=$True)]   
	[string]$log,                                       # the log file to write log
	[Parameter(Mandatory=$True)]     
	[string]$start_time                                 # the starttime of autosysjob
)
#<---------------------------------- initilize functions
$this_user=$env:username                                              # the user which is running this script
$this_path = Split-Path -Parent ($MyInvocation.MyCommand.Definition)  # the full directory path of this script
. "$this_path\functions.ps1"                                          # invoke all the fucntions to the powershell script
#<---------------------------------- get the rdcmon process
Write-Log Normal "The latest rdcmon process was started as below details." $log
ps rdcmon -ea 0|select Id,ProcessName,StartTime,@{n='Owner';e={$this_user}}|fl |Out-File -FilePath $log -Append -Encoding utf8 -Force 
#<---------------------------------- get configure VDI list
$servers_configuration_csv="C:\Users\$this_user\RDC Monitor\ServersConfiguration.csv"
$configList=@() ; Import-Csv $servers_configuration_csv -ea 0|%{$configList+=$_.computerName}
#<---------------------------------- find opened rdc sessions and compare to ServersConfiguration.csv list
$old_mstsc=$null ; $script_start_time=[datetime](("{0:yyyy-MM-dd}" -f (get-date)) + " $start_time") ; $body_template="" ; $NotSuccessInfo=""
$mstsc_process=ps mstsc -ea 0
$mstsc_process|%{
	$id=$_.id ; $this_mstsc_start_time=$_.starttime
	If( $this_mstsc_start_time -lt $script_start_time ){
	    $old_mstsc+="$id-$this_mstsc_start_time`n"
	}
}
If($old_mstsc -ne $null){
	$old_mstsc_count=$old_mstsc.split("`n").count - 1
	Write-Log Warning "Below are the $old_mstsc_count VDIs in ServersConfiguration.csv that have not been killed.`n" $log
	$old_mstsc | Out-File -FilePath $log -Append -Encoding utf8 -Force 
	$taskRunResult="WARNING"
	$NotSuccessInfo=": Not All RDC Connected"
	$body_template="There are $old_mstsc_count out of $($configList.count) VDIs that were not killed after 12 mins.`r`n`n$old_mstsc"
}
$openList=$mstsc_process.MainWindowTitle|%{($_ -split("- R"))[0].trim()}|?{$_ -ne ""}
If( ($not_connect_vdi=$configList|?{$_ -notin $openList}) -ne $null){
	$vdi=$null # format layout to put in email body and log
	$not_connect_vdi|%{$vdi+="$_`n"}
	$not_connect_vdi_count=$not_connect_vdi.count
	Write-Log Warning "Below are the $not_connect_vdi_count VDIs in ServersConfiguration.csv that have not been connected.`n" $log
	$vdi | Out-File -FilePath $log -Append -Encoding utf8 -Force 
	$taskRunResult="WARNING"
	$NotSuccessInfo=": Not All RDC Connected"
	$body_template+="There are $not_connect_vdi_count out of $($configList.count) VDIs that were not found connected after 12 mins.`r`n`n$vdi"
}
If( $old_mstsc -eq $null -and ($vdi -eq $null)){
	$taskRunResult="SUCCESS";$body_template="All the VDIS in '$servers_configuration_csv' have been found connected!"
	Write-Log Success "All the VDIS in '$servers_configuration_csv' have been found connected!" $log
}
Export-LogToAutosys $log
Send-Mailtoteam $this_user $taskRunResult $NotSuccessInfo $body_template $log $start_time
